﻿using AuthCenter.Domain;
using AuthCenter.ErorCode;
using AuthCenter.Infrastructure;
using AuthCenter_API.Write.Applications.Commands.RBAC;
using AutoMapper;
using MediatR;

namespace AuthCenter_API.Write.Applications.CommandHandlers.RBAC
{
    public class RoleAddCommandHandler : IRequestHandler<RoleAddCommand, APIResult<object>>
    {
        private readonly IBaseRepository<RoleModel> _roleRepository;
        private readonly IMapper _mapper;

        public RoleAddCommandHandler(IBaseRepository<RoleModel> roleRepository, IMapper mapper)
        {
            _roleRepository = roleRepository;
            _mapper = mapper;
        }

        public async Task<APIResult<object>> Handle(RoleAddCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            result.Code = APIEnum.AddSuccess;
            result.Message = APIEnum.AddSuccess.Desc();
            RoleModel role = _mapper.Map<RoleModel>(request);
            role.CreateName = "张三";
            role.CreateTime = DateTime.Now;
            var exist = _roleRepository.GetAll().Any(x => x.RoleName == request.RoleName&&x.IsDel==0);
            if (exist)
            {
                result.Code = APIEnum.AddFail;
                result.Message = APIEnum.AddFail.Desc() + "名称不能重复，请重新输入";
                return await Task.FromResult(result);
            }
            await _roleRepository.Add(role);
            return await Task.FromResult(result);
        }
    }
}
